package com.drcoffee.drcoffeemall.util;

import com.drcoffee.drcoffeemall.entry.ExceptionRecord;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Objects;

public class LllegalRequestUtil {

    public static ExceptionRecord processData(String request_path, String ip, String private_ip) {
        // 时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
        ExceptionRecord exceptionRecord = new ExceptionRecord();
        exceptionRecord.setDate(formattedDateTime);
        exceptionRecord.setPath(request_path);
        exceptionRecord.setIp(ip);
        String ip_address = "";
        if (!Objects.equals(ip, "") && ip != null) {
            ip_address = getIPAddress(ip);
            exceptionRecord.setIp(ip);
        } else {
            exceptionRecord.setIp("");
        }
        exceptionRecord.setAddress(ip_address);
        exceptionRecord.setPrivate_ip(private_ip);
        return exceptionRecord;
    }

    public static String getIPAddress(String ip) {
        try {
            // IP地址
            String host = "https://c2ba.api.huachen.cn";
            String api_path = "/ip";
            String appcode = "d1034421815b4659b4eb81d8e4cf3482";
            //        String ipAddress = "222.92.75.114";
            String url = host + api_path + "?ip=" + ip;
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "APPCODE " + appcode);
            HttpEntity<String> entity = new HttpEntity<>(headers);
            RestTemplate restTemplate = new RestTemplate();
            // 发起HTTP GET请求，包含自定义请求头
            ResponseEntity<String> responseEntity = restTemplate.exchange(
                    url, HttpMethod.GET, entity, String.class);
            // 处理响应
            String responseBody = responseEntity.getBody();
            System.out.println(responseBody);
            Map<String, Object> ipResponseMap = BodyToMapUtil.convertJsonToMap(responseBody);
            Map<String, String> ipMap = (Map<String, String>) ipResponseMap.get("data");
            return ipMap.get("area") + "," + ipMap.get("isp") + "," + ipMap.get("country") + "," + ipMap.get("region") + "," + ipMap.get("city");
        } catch (Exception e) {
            return "";
        }
    }
}
